/// <reference path="jquery-latest.js" />

//---------common begin----------------------
var eventbegin = function(param){ };
var eventerror = function(data){
};
var eventend = function(data){
};
function getCommonAjax(param, params, enablePost){
    param = param || "articleList";
    eventbegin(param); 
    httptype = "GET";
    if (arguments.length > 2) {
        httptype = "POST"; 
    }
    
    var options = {
        "ajax_param": param
    };
    params = params ||
    {};
    $.extend(options, params);
    $.ajax({
        type: httptype,
        url: "ajaxpage.aspx",
        data: options,
        cache: false,
        success: function(data){
			var error = $(data).find("CallbackError").text();
			if (error.length > 0) {
				alert(error);
			}
			else {
				$("#ajaxload").html("loading...").show();
				eventend(data, param);
			}
			if ($("#scodeImg")) {
				$("#scodeImg").each(function(){
					$(this).trigger("click");
				})
			}
		},
		complete:function()
		{
			$("#ajaxload").hide();
		},
        error: function(request, settings){
            alert("服务器出错,请重试");
        }
    });
}

function BaseSvcAjax(ajaxparam, params, svctype){

    eventbegin(params);
    var httptype = "POST";
    if (svctype) {
        httptype = svctype;
    }
    var options = {};
    $.extend(options, params);
    $.ajax({
        
        type: httptype,
        url: ajaxparam.url,
        data: options,
        cache: false,
        success: function(data){
            
            var dataType = typeof data;
            
            if (dataType == "string" || ajaxparam.dataType == "json") {
                $("#ajaxload").html("loading...").show();
                eventend(data, params);
               
            }
            
            else {
                alert($(data).find("CallbackError").text());
            }
        },
        complete: function(){
            $("#ajaxload").hide();
        },
        error: function(request, settings){
            alert(request.responseText);
        }
    });
}


function SvcAjax(ajaxparams, params, eventhandle, httptype){
    if (eventhandle) 
        eventhandle;
    BaseSvcAjax(ajaxparams, params, httptype);
}

function deleteEvent(){
    eventbegin = function(param){
    };
    eventend = function(data){
    };
}

function getCommonList(module){
    getCommonContent(module, {}, commonListEvent());
}

function getCommonContent(param, params, eventhandle, httptype){
    if (arguments.length < 4) 
        httptype = false;
    
    if (eventhandle) 
        eventhandle;
    if (httptype) {
        getCommonAjax(param, params, true);
    }
    else {
        getCommonAjax(param, params);
    }
	//$("#ajaxload").hide();
}

//---------common end----------------------

//-------------view begin--------------------
function sideBarEvent(){
    eventbegin = function(param){
        $("#" + param).html("loading...");
    };
    eventend = function(data, panel){
        $("#" + panel).html(data);
    };
}

function commonListEvent(){
    eventbegin = function(){
        $("#ajaxload").html("loading...").show();
    };
    eventend = function(data, panel){
		
        $("#content").html(data);
        switch (panel) {
			case "guestbooklist":
				
				NLBSGuestBook.validationAddGuestBook();
				break;
			case "userDetails":
				NLBSUser.validationUpdateUser();
				break;
		}
    };
}

function defaultContentEvent(){
    eventbegin = function(param){
        $("#ajaxload").html("loading...").show();
    };
    eventend = function(data){
        $("#content").html(data);
		
    };
}

function singleArticleEvent(){
	eventbegin = function(param){
		$("#ajaxload").html("loading...").show();
	};
	eventend = function(data){
		$("#content").html(data);
		var logID=$("#logID").val();
		if (logID) {
			NLBSComment.validationAddComment();
			
			
			SvcAjax({
				url: "/services/ArticleSvc.ashx/UpdateArticleView",
				dataType: "text"
			}, {
				logID: $("#logID").val()
			}, updateArticleViewEvent());
		}
		//window.location.hash="comments";
	};
	function updateArticleViewEvent(){
		eventend = function(){
			var viewCount=$("#logViewCount").text();
			$("#logViewCount").text(parseInt(viewCount)+1)
		}
	}
}

//-------------view end--------------------
//------------Model begin---------------------------
//---------post ajaxload begin----------------------

var NLBSArticle = {
    /**
     *
     * @param {Object} params
     */
    getContentList: function(params){
        getCommonContent("articleList", params, defaultContentEvent());
    },
    /**
     *
     */
    getDefaultContent: function(){
        this.getContentList();
    },
    /**
     *
     * @param {Object} mode
     */
    getModeContent: function(mode){
        this.getContentList({
            "mode": mode
        });
    },
    /**
     *
     */
    getSelectedContent: function(){
        this.getContentList({
            "selected": true
        });
    },
    /**
     *
     * @param {Object} id
     */
    getCategoryContent: function(id){
        this.getContentList({
            "catID": id
        });
    },
	 /**
     *
     * @param {Object} id
     */
    getUserContent: function(id){
        this.getContentList({
            "user": id
        });
    },
    /**
     *
     * @param {Object} day
     */
    getDayContent: function(day){
        this.getContentList({
            "date": day
        });
    },
    /**
     *
     * @param {Object} id
     */
    getContentByID: function(id){
        getCommonContent("singleArticle", {
            "ID": id
        }, singleArticleEvent());
        
        
    }
};
//---------post ajaxload end----------------------

//---------comment ajaxload begin----------------------
var NLBSComment = {
	
	getCommentList: function(params){
		getCommonContent("commentlist", params, commonListEvent());
	},
    addComment: function(){
        var logID = $("#logID").attr("value");
        getCommonContent("addcomment", {
            "logID": logID,
            name: $("#comm_username").val(),
            password: $("#comm_password").val(),
            message: $("#message").val(),
            scode: $("#scode").val(),
            register: $("#comm_register").attr("checked") ? true : false
        }, this.commentEvent(logID), true);
    },
    commentEvent: function(logID){
        if (logID == 0) {
            eventend = function(data){
                getCommonList("commentlist");
            };
            return;
        }
        eventend = function(data){
        
            if (logID) {
                NLBSComment.getArticleComment(logID);
            }
            else {
                $("#commentList").html(data);
                $("#comm_username,#message").val("");
                //$("#message").attr("value", "");
				var logCommentCount=$("#logCommentCount").text();
				
				$("#logCommentCount").text(parseInt(logCommentCount)+1);
            }
        };
    },
    /**
     *
     * @param {Object} logID
     */
    getArticleComment: function(logID){
        getCommonContent("articleCommentList", {
            "id": logID
        }, this.commentEvent());
    },
	/**
     *
     * @param {Object} userID
     */
    getUserComment: function(userID){
        getCommonContent("commentlist", {
            "user": userID
        }, defaultContentEvent());
    },
	/**
     *
     * @param {Object} catID
     */
    getCatComment: function(catID){
        getCommonContent("commentlist", {
            "cat": catID
        }, defaultContentEvent());
    },
    /**
     *
     * @param {Object} commentID
     * @param {Object} logID
     */
    deleteComment: function(commentID, logID){
        getCommonContent("deleteComment", {
            "id": commentID,
            "logID": logID
        }, this.commentEvent(logID), true);
    },
    validationAddComment: function(){
		$("#comm_username").addClass("required");
		$("#message").addClass("required");
		var container = $('div.errorContainer');
		$("#commentsForm").validate({
			errorContainer: container,
			errorLabelContainer: $("ol", container),
			wrapper: 'li',
			submitHandler: function(){
				NLBSComment.addComment();
			}
		});
	}
};
//---------comment ajaxload end----------------------


//---------guestBook ajaxload begin----------------------
var NLBSGuestBook = {
	getGuestBook:function(params){
		getCommonContent('guestbooklist', params, commonListEvent());
		
	},
    addGuestBook: function(gbook){
        getCommonContent("addGuestBook", {
            "name": gbook.userName,
            "message": gbook.message,
            "scode": gbook.scode
        }, this.guestBookEvent(), true);
    },
    validationAddGuestBook: function(){
		$("#comm_username").addClass("required");
		$("#message").addClass("required");
		var container = $('div.errorContainer');
		$("#commentsForm").validate({
			errorContainer: container,
			errorLabelContainer: $("ol", container),
			wrapper: 'li',
			submitHandler: function(){
				var gbook = {
					userName: $("#comm_username").val(),
					message: $("#message").val(),
					scode: $("#scode").val() ? $("#scode").val() : ""
				};
				NLBSGuestBook.addGuestBook(gbook);
			}
		});
	},
    deleteGuestBook: function(id){
        getCommonContent("deleteGuestBook", {
            "id": id
        }, this.guestBookEvent(), true);
    },
    guestBookEvent: function(){
        eventerror = function(data){
        };
        eventend = function(data){
            getCommonList("guestbooklist");
        };
    }
};
//---------guestBook ajaxload end----------------------

var NLBSTrackBack = {
	
	getTrackbackList: function(params){
		getCommonContent("trackbacklist", params, defaultContentEvent());
	},
	getContentByID: function(logID){
		getCommonContent("trackbacklist", {
			"id": logID
		}, defaultContentEvent());
	},
	deleteTrackBack: function(id){
		
		getCommonContent("deleteTrackBack", {
			"id": id
		}, this.guestBookEvent(), true);
	},
	guestBookEvent: function(){
		eventend = function(data){
			getCommonList("trackbacklist");
		};
	}
};
//---------user ajaxload begin----------------------

var NLBSUser = {
    validateUser: function(){
        var panelUser = $("#loginForm");
        var content = panelUser.find("input");
        var username = $(content[0]).val();
        var password = $(content[1]).val();
        getCommonContent("validateUser", {
            "user": username,
            "password": password,
            "scode": $("#scode").val(),
			"cookiesDay":$("#cookiesDay").val()
        }, this.validateUserEvent(), true);
    },
    validateUserEvent: function(){
        eventbegin = function(param){
        };
        eventend = function(data){
            var validate = (data.toLowerCase() == 'true');
            
            NLBSUser.setStats(validate);
            if (validate) {
                NLBSUser.showLoginStats();
                NLBSUser.showPanelUser();
            }
            else {
                alert("please login again");
            }
        };
    },
    setStats: function(stats){
        $("#stats").attr("value", stats.toString());
    },
    showPanelUser: function(){
        getCommonContent("panelUser", {}, this.panelUserEvent(), true);
    },
    panelUserEvent: function(){
        eventbegin = function(){
            $("#loginForm").html("加载中...");
        };
        eventend = function(data){
            $("#loginForm").html(data);
        };
    },
    showLoginStats: function(){
        if ($("#stats").attr("value").toLowerCase() == "true") {
            var menu = $("#menu ul").find("li");
            var login = $(menu[menu.length - 1]);
            $("#panelUser").show();
            $(login).hide();
        }
    },
    getUserDetail: function(userID){
        getCommonContent("userDetails", {
            "id": userID
        }, defaultContentEvent());
    },
    getUserEditDetail: function(userID){
        getCommonContent("userDetails", {
            "act": "edit",
            "id": userID
        }, commonListEvent());
    },
    editUserEvent: function(){
		eventbegin = function(param){
			$("#ajaxload").html("loading...").show();
		};
		eventend = function(data){
			$("#content").html(data);
			
            var hideemail = document.getElementById("hideemail");
			if (hideemail.value == "True") {
				hideemail.checked = true;
			}
			
			NLBSUser.validationUpdateUser();
		};
	},
    showRegisterForm: function(){
        getCommonContent("registerView", {}, defaultContentEvent());
    },
    showAgreeForm: function(){
        getCommonContent("registerView", {
            "act": "agree"
        }, this.registerEvent("agree"));
    },
    showSaveForm: function(){
        getCommonContent("registerView", {
            "act": "save"
        }, this.registerEvent());
    },
    registerUser: function(user){
        getCommonContent("registerUser", {
            "username": user.name,
            password: user.password,
            gender: user.genderValue,
            email: user.email,
            hideemail: user.hideemail,
            homepage: user.homepage,
            scode: user.scode
        }, this.registerEvent("save"), true);
    },
    validationRegisterUser: function(){
	
		$("#registerForm").validate({
			rules: {
				username: {
					required: true,
					minlength: 3
				},
				password: {
					required: true,
					minlength: 6
				},
				repassword: {
					required: true,
					minlength: 6
				},
				email: {
					email: true
				}
			},
			messages: {
				username: {
					required: "请输入用户名",
					minlength: "须为 3 到 24 字符"
				},
				password: {
					required: "请输入密码",
					minlength: "须为 6 到 16 字符"
				},
				repassword: {
					required: "请再次输入密码",
					minlength: "须为 6 到 16 字符",
					equalTo: "必须与上面的密码相匹配"
				},
				email: {
					email: "email地址格式错误"
				}
			},
			submitHandler: function(){
				var genders = document.getElementsByName("gender");
				var gendervalue = 0;
				
				for (var i = 0; i < genders.length; i++) {
					if (genders[i].checked) {
						gendervalue = genders[i].value;
					}
				}
				var user = {
					name: $("#username").val(),
					password: $("#password").val(),
					genderValue: gendervalue,
					email: $("#email").val(),
					hideemail: $("#hideemail").attr("checked") ? true : false,
					homepage: $("#homepage").val(),
					scode: $("#scode").val()
				};
				NLBSUser.registerUser(user);
			},
			success: function(label){
				label.html("&nbsp;").addClass("checked");
			}
		})	
	},
    registerEvent: function(act){
/*
        eventbegin = function(){
            $("#innerContent").html("loading...");
        }
*/
        eventend = function(data){
            if (act) {
                switch (act) {
                    case "save":
                        NLBSUser.showSaveForm();
                        break;
                    case "agree":
                        $("#content").html(data);
                        NLBSUser.validationRegisterUser();
                        break;
                }
                return;
            }
            $("#content").html(data);
        }
    },
    updateUser: function(user){
		
		SvcAjax({
				url: "/services/UserSvc.ashx/updateUserProFile",
				dataType: "text"
			}, {
			gender: user.genderValue,
            email: user.email,
            hideemail: user.hideemail,
            homepage: user.homepage
			},this.updateEvent(user.userID));
        
    },
	updateEvent: function(userID){
/*
		eventbegin = function(){
			$("#innerContent").html("loading...");
		}
*/
		eventend = function(data){
			NLBSUser.getUserDetail(userID);
		};
	},
	updatePassword: function(ondpass,newpass){
		
		
		SvcAjax({
				url: "/services/UserSvc.ashx/updatePassword",
				dataType: "text"
			}, {
				oldpassword: $("#oldpassword").val(),
				password:$("#password").val()
			},NLBSUser.updatePasswordEvent());
        
    },
	updatePasswordEvent: function(userID){
		eventend = function(data){
			alert("修改密码成功");
		};
	},
    validationUpdateUser: function(){
	
	
		//alert($("#changePasswordForm").attr("id"));
		
		$("#changePasswordForm").validate({
			rules: {
				oldpassword: {
					required: true,
					minlength: 3
				},
				password: {
					required: true,
					minlength: 6
				},
				repassword: {
					required: true,
					minlength: 6,
					equalTo: $("#password")
				}
			},
			messages: {
				oldpassword: {
					required: "请输入原密码",
					minlength: "须为 3 到 24 字符"
				},
				password: {
					required: "请输入密码",
					minlength: "须为 6 到 16 字符"
				},
				repassword: {
					required: "请再次输入密码",
					minlength: "须为 6 到 16 字符",
					equalTo: "必须与上面的密码相匹配"
				}
			},
			submitHandler: function(){
				NLBSUser.updatePassword();
			},
			success: function(label){
				label.html("&nbsp;").addClass("checked");
			}
		})
		
		$("#editUserProfile").validate({
			submitHandler: function(){
			
				var genders = document.getElementsByName("gender");
				var gendervalue = 0;
				
				for (var i = 0; i < genders.length; i++) {
					if (genders[i].checked) {
						gendervalue = genders[i].value;
					}
				}

				var user = {
					userID: $("#userID").attr("value"),
					genderValue: gendervalue,
					email: $("#email").val(),
					hideemail: $("#hideemail").attr("checked") ? true : false,
					homepage: $("#homepage").attr("value")
				};
				NLBSUser.updateUser(user);
				
			}
		});
	},
    deleteUser: function(userID){
    getCommonContent("deleteUser", {
            "id": userID
        }, this.deleteUserEvent(), true)
    },
	deleteUserEvent: function(){
		eventend = function(data){
			getCommonList('userlist');
		};
	}
    //userDetails
};
var Tag = {
	GetTagCloud: function(){
		getCommonContent("tagcloud", {}, defaultContentEvent());
	}
}
//---------user ajaxload end----------------------
//---------model end----------------------------
var NLBSPage = {
    ArticleCall: function(currentPage, type, url){
        if (arguments.length == 1) {
            getCommonContent("articleList", {
                page: currentPage
            }, defaultContentEvent());
            return;
        }
        switch (type) {
			case "q":
			getCommonContent("articleList", {
                    q: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "tag":
			getCommonContent("articleList", {
                    tag: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "cat":
                getCommonContent("articleList", {
                    catID: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "date":
                
                getCommonContent("articleList", {
                    date: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "selected":
                getCommonContent("articleList", {
                    selected: true,
                    page: currentPage
                }, defaultContentEvent());
			case "user":
                getCommonContent("articleList", {
                    user: url,
                    page: currentPage
                }, defaultContentEvent());
        }
    },
    CommentCall: function(currentPage, type, url){
		if (arguments.length == 1) {
			getCommonContent("commentlist", {
				page: currentPage
			}, defaultContentEvent());
			return;
		}
		switch (type) {
			case "q":
			getCommonContent("commentlist", {
                    q: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "user":
                getCommonContent("commentlist", {
                    user: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "cat":
                getCommonContent("commentlist", {
                    cat: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
        }
    },
    TrackBackCall: function(currentPage, type, url){
        if (arguments.length == 1) {
            getCommonContent("trackbacklist", {
                page: currentPage
            }, defaultContentEvent());
            return;
        }
        switch (type) {
			case "q":
			getCommonContent("trackbacklist", {
                    q: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "cat":
                getCommonContent("trackbacklist", {
                    cat: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
            case "id":
                getCommonContent("trackbacklist", {
                    id: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
        }
    },
    GuestBookCall: function(currentPage, type, url){
    if (arguments.length == 1) {
        getCommonContent("guestbooklist", {
            page: currentPage
        }, commonListEvent());
        }
        switch (type) {
			case "q":
			getCommonContent("guestbooklist", {
                    q: url,
                    page: currentPage
                }, defaultContentEvent());
                break;
                }
    },
    UserCall: function(currentPage, type, url){
        getCommonContent("userlist", {
            page: currentPage
        }, defaultContentEvent());
    }
};

function loadSideBar(panel){
    getCommonContent(panel, {}, sideBarEvent());
}
$(document).ready(function(){
    if (document.getElementById("sidebar") == null) 
        return;
        $("#panelUser").hide();
//    loadSideBar("panelCategory");
//    loadSideBar("panelArticle");
//    loadSideBar("panelComment");
//    loadSideBar("panelLink");
//    loadSideBar("panelStats");
//    loadSideBar("panelArchive");
//    
    NLBSUser.showLoginStats();
});


